package io.github.mobodev.accessbilityservicetest;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.PowerManager;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import java.util.ArrayList;

/**
 * Created by bshao on 5/5/16.
 */
public class CallVibratorAccessibilityService extends AccessibilityService {
    static PowerManager.WakeLock mLock;

    protected void onServiceConnected() {
        AccessibilityServiceInfo config = getServiceInfo();
        config.eventTypes = AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
        config.feedbackType = -1;
        ArrayList<String> list = new ArrayList<>();
        for (ApplicationInfo info : getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA)) {
//            Log.v(Utils.TAG, info.packageName);
            if (info.packageName != null && (info.packageName.contains("dialer") || info.packageName.contains("phone") || info.packageName.contains("call") || info.packageName.contains("contact"))) {
                list.add(info.packageName);
            }
        }
        Log.i(Utils.TAG, "listening to " + list.size());
        String[] packageNames = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            packageNames[i] = list.get(i);
            Log.i(Utils.TAG, "listening to " + packageNames[i]);
        }
        config.packageNames = packageNames;
        config.flags = AccessibilityServiceInfo.DEFAULT;
        setServiceInfo(config);
        PreferencesController.setOutGoingCallStarted(getApplicationContext(), false);
    }

    public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
        if (!PreferencesController.getEnableDualSim(getApplicationContext())) {
            if (PreferencesController.getOutGoingCallStarted(getApplicationContext())) {
                acquireLock(this);
            } else {
                return;
            }
        }
        Log.i(Utils.TAG, "event is called: " + accessibilityEvent.getEventType());
        Log.i(Utils.TAG, "package: " + accessibilityEvent.getPackageName());
        if (accessibilityEvent.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
            AccessibilityNodeInfo info = accessibilityEvent.getSource();
            if (info != null && info.getText() != null) {
                Log.i(Utils.TAG, "text: " + info.getText().toString());
                if ("00:00".equals(info.getText().toString()) || "00:01".equals(info.getText().toString())) {
                    Log.i(Utils.TAG, "Call start Detected");
                    handlVibrate(getApplicationContext(), true);
                }
                info.recycle();
            }
        }
    }

    public static void handlVibrate(Context context, boolean isStartCall) {
        PreferencesController.setOutGoingCallStarted(context, false);
        releaseLock();
        if (!Utils.disableVibrationWithHeadset(context) && !Utils.disableVibrationWithApproximity(context)) {
            Utils.vibrateDevice(context, isStartCall);
        }
    }

    public static void acquireLock(Context context) {
        if (mLock == null) {
            Log.v(Utils.TAG, "Wake lock acquired");
            mLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).newWakeLock(26, "no sleep");
            mLock.acquire();
        }
    }

    public static void releaseLock() {
        Log.v(Utils.TAG, "Wake lock released");
        if (mLock != null) {
            mLock.release();
            mLock = null;
        }
    }

    public void onInterrupt() {
        releaseLock();
    }

    public boolean onUnbind(Intent intent) {
        releaseLock();
        return super.onUnbind(intent);
    }

    public void onDestroy() {
        releaseLock();
        super.onDestroy();
    }
}
